<template>
  <div :id="id" style="height:100%;width:100%;"></div>
</template>

<script>
  import echarts from 'echarts'

  let listData = [
    {value: 100, name: '100%'},
    {value: 0, name: ''}
  ]
  export default {
    name: '',
    data () {
      return {
        chart: null
      }
    },
    props: {
      charData: {
        default: () => {
          return listData
        }
      },
      id: String
    },
    beforeUpdate: function () {
      this.drawPie(this.id)
    },
    watch: {
      charData: function (val, oldVal) {    // 监听charData，当放生变化时，触发这个回调函数绘制图表
        console.log('new: %s, old: %s', val, oldVal)
        if (val && Array.isArray(val)) {
          listData = val
          this.drawPie(this.id)
          return val
        }
        let otherVal = 100 - val
        console.log(otherVal)
        listData = [
          {value: val, name: val + '%'},
          {value: otherVal, name: ''}
        ]
        this.drawPie(this.id)
      }
    },
    methods: {
      drawPie (id) {
        this.charts = echarts.init(document.getElementById(id))
        let _data = {
          series: [
            {
              name: '',
              type: 'pie',
              color: ['#0b7a04', '#e20001'],
              selectedMode: false,
              radius: [0, '80%'],
              clickable: false,
              label: {
                position: 'inner'
              },
              labelLine: {
                show: false
              },
              data: listData
            }
          ]
        }
        this.charts.setOption(_data)
      }
    },
    mounted() {
      this.$nextTick(function () {
        this.drawPie(this.id)
      })
    }
  }
</script>

<style scoped lang="">

</style>
